using Blazorise;

using Microsoft.AspNetCore.Components;

using Volo.Abp.AspNetCore.Components.Web.Configuration;

using WL.Think.Abp.Localization;
using WL.Think.Abp.OpenIddict.Dtos;
using WL.Think.Abp.OpenIddict.Services;

namespace WL.Think.Abp.OpenIddict.Pages.Applications
{
    public partial class ApplicationManagerModal
    {
        [Inject] protected ICurrentApplicationConfigurationCacheResetService CurrentApplicationConfigurationCacheResetService { get; set; }
        [Inject] protected IApplicationAppService appService { get; set; }
        [Inject] protected IScopeAppService scopeService { get; set; }

        protected Modal modal;
        protected Validations ValidationsRef;
        protected ApplicationCreateUpdateDto Entity;
        protected bool IsEditMode = false;
        protected Guid? EditingEntityId;
        protected string? Title;
        protected string? RedirectUrl;
        protected string? LogoutRedirectUrl;
        protected string SelectedTab = "basic";
        protected List<ScopeDto> ScopeList = new List<ScopeDto>();
        protected IReadOnlyList<string> SelectedScopeList { get; set; }

        public ApplicationManagerModal()
        {
            LocalizationResource = typeof(ThinkResource);
            Entity = new ApplicationCreateUpdateDto();
        }

        /// <summary>
        /// 组件初始化
        /// </summary>
        /// <returns></returns>
        protected override async Task OnInitializedAsync()
        {
            await base.OnInitializedAsync();
            await LoadScopeAsync();
        }


        /// <summary>
        /// 打开组件
        /// </summary>
        /// <param name="applicationId"></param>
        /// <returns></returns>
        public virtual async Task OpenAsync(Guid? applicationId = null)
        {
            try
            {
                IsEditMode = applicationId.HasValue;
                EditingEntityId = applicationId;
                Entity = new ApplicationCreateUpdateDto();
                Title = L["New"];
                if (IsEditMode)
                {
                    var item = await appService.GetAsync(applicationId!.Value);
                    Title = L["Edit"] + "_" + item.ClientId;
                    Entity = MapToEditingEntity(item);
                }
                SetSelectedScopeList();
                await InvokeAsync(async () =>
                {
                    StateHasChanged();
                    await modal.Show();
                });
            }
            catch (Exception ex)
            {
                await HandleErrorAsync(ex);
            }
        }

        /// <summary>
        /// 关闭组件
        /// </summary>
        /// <returns></returns>
        public virtual Task CloseAsync()
        {
            SelectedTab = "basic";
            return InvokeAsync(modal.Hide);
        }

        /// <summary>
        /// 保存提交
        /// </summary>
        /// <returns></returns>
        protected virtual async Task SaveAsync()
        {
            try
            {
                if(!await ValidationsRef.ValidateAll())
                {
                    return;
                }

                Entity.Scopes = SelectedScopeList.ToList();
                if (IsEditMode) {
                    await appService.UpdateAsync(EditingEntityId!.Value, Entity);
                }
                else
                {
                    await appService.CreateAsync(Entity);
                }
                await CurrentApplicationConfigurationCacheResetService.ResetAsync();
                await InvokeAsync(modal.Hide);
                await Notify.Success(L["SavedSuccessfully"]);
            }
            catch (Exception ex)
            {
                await HandleErrorAsync(ex);
            }
        }

        /// <summary>
        /// 关闭模态窗口中
        /// </summary>
        /// <param name="eventArgs"></param>
        /// <returns></returns>
        protected virtual Task ClosingModal(ModalClosingEventArgs eventArgs)
        {
            eventArgs.Cancel = eventArgs.CloseReason == CloseReason.FocusLostClosing;
            return Task.CompletedTask;
        }

        /// <summary>
        /// 实体映射，把DTO转换乘编辑DTO
        /// </summary>
        /// <param name="entityDto"></param>
        /// <returns></returns>
        protected virtual ApplicationCreateUpdateDto MapToEditingEntity(ApplicationDto entityDto)
        {
            return ObjectMapper.Map<ApplicationDto, ApplicationCreateUpdateDto>(entityDto);
        }

        /// <summary>
        /// 授权方式改变
        /// </summary>
        /// <param name="value"></param>
        /// <param name="grantType"></param>
        protected virtual void OnGrantTypeChanged(bool value, string grantType)
        {
            if(value)
            {
                Entity.GrantTypes.Add(grantType);
            }
            else
            {
                Entity.GrantTypes.Remove(grantType);
            }
        }

        /// <summary>
        /// 添加重定向地址
        /// </summary>
        protected virtual void OnRedirectUrisClicked()
        {
            if(!RedirectUrl.IsNullOrEmpty())
            {
                Entity.RedirectUris.Add(RedirectUrl);
                RedirectUrl = "";
            }
        }

        /// <summary>
        /// 添加退出登录重定向地址
        /// </summary>
        protected virtual void OnPostLogoutRedirectUrisClicked()
        {
            if(!LogoutRedirectUrl.IsNullOrEmpty())
            {
                Entity.PostLogoutRedirectUris.Add(LogoutRedirectUrl);
                LogoutRedirectUrl = "";
            }
        }


        /// <summary>
        /// 改变选项卡
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        protected virtual Task OnSelectedTabChanged(string name)
        {
            SelectedTab = name;
            return Task.CompletedTask;
        }

        /// <summary>
        /// 加载范围数据
        /// </summary>
        /// <returns></returns>
        private async Task LoadScopeAsync()
        {
            ScopeList = new List<ScopeDto>();
            var result = await scopeService.GetListAsync(new ScopePagedDto
            {
                MaxResultCount = 1000
            });
            if (result.TotalCount > 0) {
                ScopeList = result.Items.ToList();
            }
        }

        /// <summary>
        /// 加载已选择的范围列表
        /// </summary>
        /// <returns></returns>
        private void SetSelectedScopeList()
        {
            SelectedScopeList = Entity.Scopes;
        }
    }
}
